<template>
  <div class="app-container">
    <el-row :gutter="15" class="mb8">
      <el-form :inline="true" :model="formData" class="el-form-search">
        <!--设备选择-->
        <!--设备选择-->
        <el-form-item class="el-form-search-item" label="设备" porp="device">
          <el-select v-model="formData.device" clearable filterable placeholder="请选择设备类型" @change="setChannelList">
            <el-option v-for="device in deviceList" :key="device.zhGuid" :label="device.devName"
              :value="device.zhGuid" />
          </el-select>
        </el-form-item>
        <!--通道选择-->
        <el-form-item class="el-form-search-item" label="通道" porp="channel">
          <el-select v-model="formData.tdGuid" clearable filterable placeholder="请选择设备类型">
            <el-option v-for="channel in channelList" :key="channel.tdGuid" :label="channel.channelName"
              :value="channel.tdGuid" />
          </el-select>
        </el-form-item>

        <el-form-item class="el-form-search-item" label="时间" porp="timeRange">
          <!-- 时间选择 -->
          <el-date-picker v-model="formData.timeRange" :pickerOptions="pickerOptions" end-placeholder="结束时间" format="yyyy-MM-dd HH:mm:ss"
            range-separator="至" start-placeholder="开始时间" style="width: 400px" type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <!-- 查询按钮 -->
        <el-button icon="el-icon-search" size="mini" type="primary" @click="getWaveList">搜索
        </el-button>
      </el-form>
    </el-row>

    <el-table v-loading="loading" :data="waveList" height="calc(100vh - 200px)" stripe style="width: 100%" border>
      <el-table-column type="index" label="#" width="50" align="center">
        <template slot-scope="scope">
          {{
            (formData.pageNum - 1) * formData.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column>
      <el-table-column label="时间" prop="timedate" align="center">
      </el-table-column>
      <el-table-column align="center" label="设备" prop="channelInfo.devInfo.devName"></el-table-column>
      <el-table-column align="center" label="通道" prop="channelInfo.channelName"></el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <template slot-scope="scope">
          <el-button icon="el-icon-view" size="mini" type="text" @click="getByTdGuid(scope.row)">查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <pagination v-show="total > 0" :limit.sync="formData.pageSize" :page.sync="formData.pageNum" :total="total"
      @pagination="getWaveList" />
    <!-- 对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" :title="title" :visible.sync="dialogVisible" width="80%">
      <wave-form-visualization :wave-data="waveformData" :devName="devName" :channelName="channelName" />
    </el-dialog>
  </div>
</template>

<script>
import { getWaveByPage, getWaveByTdGuide } from "@/api/data_analysis/dbWave";
import { getDeviceListFold } from "@/api/device/device";
import WaveFormVisualization from "./component/WaveformVisualization.vue";
import { mapState } from "vuex";

export default {
  components: {
    WaveFormVisualization,
  },

  computed: {
    ...mapState({
      deviceList: state => state.user.deviceList, // 从 Vuex 中获取 deviceList
    })
  },
  data() {
    return {
      formData: {
        pageNum: 1,
        pageSize: 30,
        tdGuid: '',
        timeRange: [
          new Date(2025, 0, 20), // 月份从0开始（0=1月）
          new Date(2025, 0, 22),
        ],
        device: "",
        channel: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          }, {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // deviceList: [],
      channelList: [],
      waveList: [],
      tables: [
        { value: "base", label: "原始数据" },
        { value: "avg", label: "平均值" },
        { value: "max", label: "最大值" },
        { value: "min", label: "最小值" },
      ],
      loading: false,
      total: 0,
      // 波形折线图
      dialogVisible: false,
      title: "波形数据折线图",
      waveformData: [],
      devName: "",
      channelName: "",
      dateTime: "",
    };
  },
  mounted() {
    this.getWaveList();
    let obj = this.$store.state.filterConditions.filterConditions
    console.log("obj", obj);

    if (obj) {
      this.formData.device = obj.device
      this.formData.timeRange = obj.datetime || [];
      let device = this.deviceList.find(f => f.zhGuid == this.formData.device)
      if (device) {
        this.channelList = device.channelList;
        this.formData.channel = obj.channel
        // this.formData.selectedTable = obj.selectedTable
      }
    }
    // this.getDeviceList();
  },
  watch: {
    formData: {
      handler(newForm, oldForm) {
        let obj = Object.assign({}, newForm);
        obj.datetime = newForm.timeRange;
        this.$store.commit("UPDATE_FILTER_CONDITIONS", obj);
        console.log(this.$store.state.filterConditions.filterConditions);
      },
      deep: true,
    },
  },
  methods: {
    getWaveList() {
      if (this.formData.timeRange && this.formData.timeRange.length > 0) {
        this.formData.startTime = this.formData.timeRange[0]
        this.formData.endTime = this.formData.timeRange[1]
      } else {
        this.formData.startTime = ""
        this.formData.endTime = ""
      }
      getWaveByPage(this.formData).then((res) => {
        console.log(res);
        this.waveList = res.rows;
        this.total = res.total;
          this.$refs.elTable.doLayout();
      });
    },
    getByTdGuid(row) {
      this.dialogVisible = true;
      getWaveByTdGuide({ tdGuid: row.tdGuid, timedate: row.timedate }).then(
        (res) => {
          console.log(res);

          // 1. 解码Base64为二进制数组
          const binaryString = atob(res.data.wave);
          const bytes = new Uint8Array(binaryString.length);
          for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
          }

          // 3. 创建一个Int8Array来正确处理有符号字节
          const signedBytes = new Int8Array(bytes.buffer);

          // 现在signedBytes数组中的值会正确表示负数
          // 例如：如果原始数据中有-1，在signedBytes中会正确显示为-1
          // 而在普通的Uint8Array中会显示为255

          // console.log("有符号解析结果:", Array.from(signedBytes));
          // console.log("无符号解析结果:", Array.from(bytes));
          console.log(row)
          this.waveformData = Array.from(signedBytes);
          this.channelName = row.channelInfo.channelName;
          this.devName = row.channelInfo.devInfo.devName;
          this.id = row.id;
        }
      );
    },
    getDeviceList() {
      //获取设备列表
      getDeviceListFold().then((res) => {
        console.log(res);
        this.deviceList = res.rows;
        if (this.formData.device !== null || this.formData.device !== "") {
          this.channelList = this.deviceList.filter((item) => {
            return item.zhGuid === this.formData.device;
          })[0].channelList;
        }
      });
    },
    setChannelList(selectedValue) {
      let obj = this.deviceList.find(f => f.zhGuid == selectedValue)
      this.channelList = obj ? obj.channelList : [];
      this.formData.tdGuid = this.channelList[0]?.tdGuid;
      console.log("obj", this.formData.tdGuid);

    }
  },
};
</script>

<style lang="scss" scoped>
.autocomplete-item-disabled {
  color: #999;
  cursor: not-allowed;
  pointer-events: none;
  /* 禁止点击 */
}
</style>
